package com.study.common.exception;

import com.study.common.entity.LoginException;
import com.study.common.entity.ResultInfo;
import com.study.common.utils.ResultUtils;
import com.study.common.enumerate.ExceptionInfo;
import com.study.common.enumerate.Log4jInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author 谭永超 [www.tanyongchao.tk:8090/SumDome/index]
 * @Date 2018/8/28 16:47
 * @Description 获取错误信息捕获
 */
@ControllerAdvice
public class ExceptionHandle {
    private static final Log log = LogFactory.getLog(ExceptionInfo.class);

    // 捕获哪个类的异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultInfo handler(Exception e) {
        if (e instanceof MyError) {
            LoginException demoException = (LoginException) e;
            log.info(Log4jInfo.HEAD.getMessage() + "错误信息:" + demoException.getMessage());
            return ResultUtils.error(demoException.getExceptionInfo());
        }
        log.info(Log4jInfo.HEAD.getMessage() + "错误信息:" + e.getMessage());
//        工具类处理
        String reg = "[\\u4e00-\\u9fa5]+";
        if(e.getMessage()!=null){
        if(e.getMessage().matches(reg)){
            ExceptionInfo.UNKNOW_EXCEPTION.setMessage(e.getMessage());

        }else{
            String reg1 = "[^\\u4e00-\\u9fa5]";
            String str =  e.getMessage();
            str = str.replaceAll(reg1, "");
            ExceptionInfo.UNKNOW_EXCEPTION.setMessage(str);
        }
        }else{
            ExceptionInfo.UNKNOW_EXCEPTION.setMessage(e.getMessage());
        }
        return ResultUtils.error(ExceptionInfo.UNKNOW_EXCEPTION);
    }
}
